package com.isoft.airportsystem.controller.system;

import com.isoft.airportsystem.annotation.RequiresPermission;
import com.isoft.airportsystem.common.change.Result;
import com.isoft.airportsystem.entity.system.Permission;
import com.isoft.airportsystem.service.system.PermissionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 权限管理控制器
 */
@Slf4j
@RestController
@RequestMapping("/api/system/permission")
@CrossOrigin(origins = {"http://localhost:8080", "http://localhost:3000", "http://localhost:5173"}, allowCredentials = "true")
public class PermissionController {

    @Autowired
    private PermissionService permissionService;

    /**
     * 查询权限树
     */
    @RequiresPermission("system:permission:list")
    @GetMapping("/tree")
    public Result<List<Permission>> tree() {
        List<Permission> tree = permissionService.selectPermissionTree();
        return Result.success(tree);
    }

    /**
     * 查询菜单列表
     */
    @RequiresPermission("system:permission:list")
    @GetMapping("/menu")
    public Result<List<Permission>> menu() {
        List<Permission> menus = permissionService.selectMenuList();
        return Result.success(menus);
    }

    /**
     * 根据用户ID查询菜单列表
     */
    @GetMapping("/menu/user")
    public Result<List<Permission>> userMenu() {
        // 这里需要从Token中获取用户ID，暂时返回所有菜单
        List<Permission> menus = permissionService.selectMenuList();
        return Result.success(menus);
    }

    /**
     * 根据ID查询权限
     */
    @RequiresPermission("system:permission:query")
    @GetMapping("/{permissionId}")
    public Result<Permission> getById(@PathVariable Long permissionId) {
        Permission permission = permissionService.getById(permissionId);
        return Result.success(permission);
    }

    /**
     * 新增权限
     */
    @RequiresPermission("system:permission:add")
    @PostMapping
    public Result<?> add(@RequestBody Permission permission) {
        boolean result = permissionService.insertPermission(permission);
        return result ? Result.success("新增成功") : Result.fail("新增失败");
    }

    /**
     * 修改权限
     */
    @RequiresPermission("system:permission:edit")
    @PutMapping
    public Result<?> update(@RequestBody Permission permission) {
        boolean result = permissionService.updatePermission(permission);
        return result ? Result.success("修改成功") : Result.fail("修改失败");
    }

    /**
     * 删除权限
     */
    @RequiresPermission("system:permission:remove")
    @DeleteMapping("/{permissionId}")
    public Result<?> delete(@PathVariable Long permissionId) {
        boolean result = permissionService.deletePermissionById(permissionId);
        return result ? Result.success("删除成功") : Result.fail("删除失败");
    }
}